package com.it.controller;

import com.it.BeanFactory;
import com.it.base.ViewBaseServlet;
import com.it.utils.StringUtil;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("*.do")
public class DispatcherServlet extends ViewBaseServlet {


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        //获取*.do的path
        String path = request.getServletPath().substring(1, request.getServletPath().length() - 3);
        //拿到controller对象
        BeanFactory factory = (BeanFactory) getServletContext().getAttribute("factory");
        Object object = factory.getBean(path);
        String operate = request.getParameter("operate");
//        if (StringUtil.isEmpty(operate)) {
//            operate = "queryByGet";
//        }
        //获取controller对象 所有方法
        Method[] methods = object.getClass().getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            if (methods[i].getName().equals(operate)) {
                try {
                    String result = (String) methods[i].invoke(object, request);
                    if (result.contains(".do")) {
                        response.sendRedirect(result);
                    } else {
                        super.processTemplate(result, request, response);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
        }

    }
}
